package com.itlaoqi.rabbitmq.springboot;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
public class MessageConsumer {
    //用于声明定义消息接受的队列与exchange绑定的信息
    //再springboot中，消费者段使用注解获取消息
    @RabbitListener(
          bindings = @QueueBinding(
                  value=@Queue(value = "springboot-queue",durable = "true"),
                  exchange = @Exchange(value = "springboot-exchange",durable = "true",type = "topic"),
                  key = "#"
          )
    )
    //用于接受消息的方法
    @RabbitHandler//通知springboot下面的方法用户接受消息，这个方法运行后，将处于等待的状态，
    //有新的消息进来就会自动触发下面的方法处理消息
    //payload 代表运行时将消息反序列化后注入到后的参数中
    public void handleMessage(@Payload Employee employee, Channel channel, @Headers Map<String,Object> headers){
        System.out.println("===================================================");
        System.out.println("接收到" + employee.getEmpno() + ":" + employee.getName());
        //所偶遇消息处理后必须进行消息的ack,channel
        Long tag = (Long)headers.get(AmqpHeaders.DELIVERY_TAG);
        try {
            channel.basicAck(tag,false);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("===================================================");

    }
}




















